<template>
  <div class="flexContent">
    <!-- 非标品档案 -->
    <div class="searchBox">

      <el-form class="demo-form-inline" label-position="right" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品名称">
                  <el-input v-clearEmoji v-model.trim="name" clearable style="width: 95%" placeholder="请输入名称/助记符/一维码"
                    @keyup.enter.native="searchFn" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品状态">
                  <el-select v-model="productState" style="width: 95%" clearable placeholder="请选择商品状态">
                    <el-option value="0" label="正常" />
                    <el-option value="1" label="停用" />
                    <el-option value="2" label="淘汰" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品分类">
                  <el-select @click.native="getCategoryList" v-model="category" filterable clearable
                    popper-class="eloption" style="width: 95%">
                    <el-option v-for="(val, key) in categoryList" :key="key" :value="key" :label="val" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="供应商">
                  <el-select @click.native="getSCMList" v-model="supplierId" filterable clearable popper-class="eloption"
                    style="width: 95%">
                    <el-option v-for="firstSupplier in firstSupplierList" :key="firstSupplier.id"
                      :value="firstSupplier.id" :label="firstSupplier.name" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="emptyFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
        <!-- <el-row :gutter="20" type="flex" justify="end">
          <el-col :span="8">
            <el-form-item>
              <el-button @click.stop="searchFn">搜索</el-button>
              <el-button @click.stop="emptyFn">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
    </div>
    <el-button class="addBtn" @click="addFn" v-has="'genericGoods_add'">新增</el-button>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1" align="center"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          size="medium">
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column field="name" title="商品名称" :min-width="elTableAdaptationWidth('name', genericGoodsInfoList)" />
          <vxe-column field="categoryName" title="商品分类" min-width="150" />
          <vxe-column field="supplierName" title="供应商" min-width="150">
            <template v-slot="{ row }">
              <span>{{ row.supplierName ? row.supplierName : '-' }}</span>
            </template>
          </vxe-column>
          <vxe-column field="unit" title="销售单位" width="100">
            <template v-slot="{ row }">
              <span v-if="row.unit === '0'">KG</span>
              <span v-if="row.unit === '1'">数量</span>
            </template>
          </vxe-column>
          <vxe-column field="purchasePrice" title="进货价(元)" min-width="150" />
          <vxe-column field="outboundPrice" title="出仓价(元)" min-width="150" />
          <vxe-column field="status" title="商品状态" width="100">
            <template v-slot="{ row }">
              <el-tag v-if="row.status === '0'" type="success" size="small">正常</el-tag>
              <el-tag v-if="row.status === '1'" type="info" size="small">停用</el-tag>
              <el-tag v-if="row.status === '2'" type="danger" size="small">淘汰</el-tag>
            </template>
          </vxe-column>
          <vxe-column v-if="$showFn([
            'genericGoods_edit',
            'genericGoods_detail',
            'genericGoods_del',
            'update_genericprice'
          ])
            " title="操作" fixed="right" width="200">
            <template v-slot="{ row }">
              <el-button type="text" v-has="'genericGoods_edit'" @click.stop="edit(row)">修改</el-button>
              <el-button type="text" style="margin-right: 5px" @click.stop="detail(row)"
                v-has="'genericGoods_detail'">详情</el-button>
              <el-button type="text" v-if="row.status !== '0'" style="color: red" @click="$delFn('商品', del, row)"
                v-has="'genericGoods_del'">删除</el-button>
              <el-button type="text" v-has="'update_genericprice'" @click="updatePrice(row)">改价</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,->, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-dialog title="调价" :visible.sync="dialogFormVisible" width="30%" @close="closeDialog">
      <el-form :model="priceForm" :rules="goodsRules" ref="priceForm" label-width="120px">

        <el-form-item label="进货价(元)" prop="purchasePrice">
          <el-input v-model="priceForm.purchasePrice" placeholder="请输入进货价"></el-input>
          <el-button type="primary" @click="updatepurchasePrice" style="margin-left: 20px;">确 定</el-button>
        </el-form-item>
        <el-form-item label="出仓价(元)" prop="outboundPrice">
          <el-input v-model="priceForm.outboundPrice" placeholder="请输入出仓价"></el-input>
          <el-button type="primary" @click="updateGoodsoutboundPrice" style="margin-left: 20px;">确 定</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
  </div>
</template>

<script>
import { getDictValueAndNameSource } from "@/api/dictionary";
import { getSCMList } from '@/api/scm';
import { getGenericGoodsList, genericGoodsDelete, genericGoodsPriceEdit } from "@/api/genericGoods";
export default {
  name: "GenericGoodsInfo",
  data() {
    return {
      genericGoodsInfoList: [],
      sKeywords: "",
      name: "",
      productState: "",
      category: "",
      isSearch: false,
      categoryList: [],
      firstSupplierList: [],
      supplierId: '',
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      dialogFormVisible: false,
      priceForm: {
        type: '0',
        purchasePrice: '',
        outboundPrice: ''
      },
      goodsRules: {
        purchasePrice: [
          {
            required: true,
            message: '请输入商品进货价',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
            message: '进货价只能是数字或小数',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 10,
            message: '进货价应为1-10位数字',
            trigger: 'blur'
          },
          // {
          //   // message: "协议进价不能大于出仓价",
          //   trigger: "change",
          //   validator: (rule, value, callback) => {
          //     if (this.priceForm.outboundPrice <= value) {
          //       callback(new Error('进货价不能大于等于出仓价'));
          //     } else {
          //       callback();
          //     }
          //   },
          // }
        ],
        outboundPrice: [
          {
            required: true,
            message: '请输入商品出仓价',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
            message: '出仓价只能是数字或小数',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 10,
            message: '出仓价应为1-10位数字',
            trigger: 'blur'
          },
          // {
          //   // message: "进货价不能大于出仓价",
          //   trigger: "change",
          //   validator: (rule, value, callback) => {
          //     if (this.priceForm.purchasePrice >= value) {
          //       callback(new Error('进货价不能大于等于出仓价'));
          //     } else {
          //       callback();
          //     }
          //   },
          // }
        ],
      }
    };
  },
  created() {
    // this.getCategoryList();
    this.getGenericGoodsList();
  },
  methods: {
    async getSCMList() {
      const res = await getSCMList();
      if (res.code === 200) {
        const data = res.data;
        this.firstSupplierList = data.list;
      }
    },
    async getCategoryList() {
      const res = await getDictValueAndNameSource("NONSTANDARD_CATEGORY");
      this.categoryList = res.data;
      console.log(this.categoryList, "this.categoryList");
    },
    async getGenericGoodsList() {
      if (!this.isSearch) {
        this.category = "";
        this.name = "";
        this.productState = "";
        this.supplierId = "";
      }
      const res = await getGenericGoodsList({
        ...this.page,
        category: this.category,
        name: this.name,
        status: this.productState,
        supplierId: this.supplierId
      });
      if (res.code === 200) {
        const data = res.data;
        console.log(res, "res");
        this.genericGoodsInfoList = data.list;
        const $table = this.$refs.xTable1
        $table.loadData(this.genericGoodsInfoList);
        this.page.pageSize = data.pageSize;
        this.page.pageNum = data.pageNum;
        this.page.total = data.total;
        console.log("列表", this.genericGoodsInfoList);
      } else {
        // this.$message.error(res.msg);
      }
    },
    async searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };

      this.isSearch = true;
      this.getGenericGoodsList();
    },
    emptyFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = false;
      this.name = "";
      this.category = "";
      this.productState = "";
      this.supplierId = "";
      this.getGenericGoodsList();
    },
    addFn() {
      this.$router.push({
        path: "addGenericGoods",
        query: {
          routeType: "add",
        },
      });
    },
    async del(row) {
      const res = await genericGoodsDelete({ id: row.id });
      if (res.code === 200) {
        this.$message.success("删除成功");
        if (this.genericGoodsInfoList.length === 1 && this.page.pageNum > 1)
          this.page.pageNum--;
        this.getGenericGoodsList();
      } else {
        // this.$message.error(res.message);
      }
    },
    edit(row) {
      this.$router.push({
        path: "editGenericGoods",
        query: {
          routeType: "edit",
          id: row.id,
        },
      });
    },
    detail(row) {
      this.$router.push({
        path: "genericGoodsDetails",
        query: {
          routeType: "detail",
          id: row.id,
        },
      });
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      this.getGenericGoodsList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getGenericGoodsList();
    },
    updatePrice(row) {
      this.selectedRow = row
      this.$set(this.priceForm, 'purchasePrice', String(row.purchasePrice))
      this.$set(this.priceForm, 'outboundPrice', String(row.outboundPrice))
      this.dialogFormVisible = true
      // this.$refs.priceForm.resetFields()
    },
    closeDialog() {
      this.$refs.priceForm.resetFields()
      this.dialogFormVisible = false
    },
    async updatepurchasePrice() {
      this.priceForm.type = '0'
      this.$refs.priceForm.validate(async (isOk) => {
        if (isOk) {
          let newPrice = ''
          if (this.priceForm.type == '0') {
            newPrice = this.priceForm.purchasePrice
            if (newPrice >= this.selectedRow.outboundPrice) {
              this.$confirm(`当前进货价大于出仓价, 确认修改吗?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(async () => {
                  const res = await genericGoodsPriceEdit({
                    newPrice,
                    priceType: this.priceForm.type,
                    commodityId: this.selectedRow.id
                  })
                  if (res.code === 200) {
                    this.$message.success(res.message)
                    this.$set(this.selectedRow, 'purchasePrice', String(newPrice))
                    // this.closeDialog()
                    this.getGenericGoodsList()
                  }
                })
                .catch(() => { });
            } else {
              const res = await genericGoodsPriceEdit({
                newPrice,
                priceType: this.priceForm.type,
                commodityId: this.selectedRow.id
              })
              if (res.code === 200) {
                this.$message.success(res.message)
                this.$set(this.selectedRow, 'purchasePrice', String(newPrice))
                // this.closeDialog()
                this.getGenericGoodsList()
              }
            }
          }
        }
      })
    },
    async updateGoodsoutboundPrice(type) {
      this.priceForm.type = '1'
      this.$refs.priceForm.validate(async (isOk) => {
        if (isOk) {
          let newPrice = ''
          console.log('1111');
          newPrice = this.priceForm.outboundPrice
          if (newPrice <= this.selectedRow.purchasePrice) {
            this.$confirm(`当前出仓价小于进货价, 确认修改吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(async () => {
                const res = await genericGoodsPriceEdit({
                  newPrice,
                  priceType: this.priceForm.type,
                  commodityId: this.selectedRow.id
                })
                if (res.code === 200) {
                  this.$message.success(res.message)
                  this.$set(this.selectedRow, 'outboundPrice', String(newPrice))
                  // this.closeDialog()
                  this.getGenericGoodsList()
                }
              })
              .catch(() => { });
          } else {
            const res = await genericGoodsPriceEdit({
              newPrice,
              priceType: this.priceForm.type,
              commodityId: this.selectedRow.id
            })
            if (res.code === 200) {
              this.$message.success(res.message)
              // this.closeDialog()
              this.$set(this.selectedRow, 'outboundPrice', String(newPrice))
              this.getGenericGoodsList()
            }
          }

          // if()
        }
      })
    }
  },
};
</script>

<style scoped lang="scss"></style>
